#include "tools/command_line_utils.h"

// 创建命令行结构
cef_command_line_t *command_line_create_t() {
    LOG_DEBUG("start");
    return cef_command_line_create();
}
// 初始化
void command_line_init_t(cef_command_line_t *self, int argc, char *argv[]) {
    LOG_INFO("start");
// windows
#if defined(OS_WIN)
    // 获取系统命令行字符串   LPWSTR=> WCHAR => wchar_t => unsigned short
    LPWSTR cmd_line_w = GetCommandLineW();
    // 转换为CEF字符串结构
    cef_string_t cef_cmd_line = {};
    cef_string_set(cmd_line_w, wcslen(cmd_line_w), &cef_cmd_line, 1);

    cef_string_utf8_t cef_cmd_line_utf8 = {};
    cef_string_utf16_to_utf8(cef_cmd_line.str, cef_cmd_line.length, &cef_cmd_line_utf8);
    LOG_DEBUG("cmd: %s", cef_cmd_line_utf8.str);
    // 初始化命令行
    self->init_from_string(self, &cef_cmd_line);
    // 清理临时字符串
    cef_string_clear(&cef_cmd_line);
    cef_string_utf8_clear(&cef_cmd_line_utf8);
    LOG_DEBUG("windows init end");

#else

#endif
    LOG_DEBUG("end");
}

// 判断进程类型
// mian 0
// redderer 1
// utility 2
// gpu-process 3
// other 4
int hash_process(cef_command_line_t *self) {
    LOG_DEBUG("start");

    int type = -1;
    cef_string_t switch_name = {};
    cef_string_utf8_to_utf16("type", strlen("type"), &switch_name);
    int hash = self->has_switch(self, &switch_name);
    LOG_DEBUG("hash %d", hash);
    // 是否是主进程
    if (!hash) {
        LOG_DEBUG("--type=main");
        type = 0;
    } else {
        // 获取type值
        cef_string_userfree_t type_value = self->get_switch_value(self, &switch_name);
        // 比较字符串值
        if (type_value) {
            cef_string_utf8_t type_utf8 = {};
            cef_string_utf16_to_utf8(type_value->str, type_value->length, &type_utf8);

            if (strcmp(type_utf8.str, "renderer") == 0) {
                LOG_DEBUG("--type=renderer");
                type = 1;
            } else if (strcmp(type_utf8.str, "utility") == 0) {
                LOG_DEBUG("--type=utility");
                type = 2;
            } else if (strcmp(type_utf8.str, "gpu-process") == 0) {
                LOG_DEBUG("--type=gpu");
                type = 3;
            } else {
                LOG_DEBUG("--type=other");
                type = 4;
            }

            cef_string_utf8_clear(&type_utf8);
            cef_string_userfree_free(type_value);
        } else {
            return 2;
        }
    }
    LOG_DEBUG("process type end %d", type);
    cef_string_clear(&switch_name);
    return type;
}
